﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using A.Enum;
using Fashion.Common.Const;
using Fashion.Common.Util;
using Fashion.Models;
using Fashion.Models.Model;

namespace Fashion.Controllers
{
    public class AccountController : BaseController
    {
        private AccountRepository _repository;

        public AccountController()
        {
            _repository = new AccountRepository();
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (!ModelState.IsValid)
                return View(model);
            Account account = _repository.FindAccountByUserName(model.UserName);
            if (account != null)
            {
                ViewData[ViewDataName.ErrorMessage] = "Tài khoản này đã tồn tại";
                return View(model);
            }
            else
            {
                account = new Account();
                account.UserName = model.UserName;
                account.Password = model.Password;
                account.Email = model.Email;
                account.FirstName = model.FirstName;
                account.LastName = model.LastName;
                account.DateTimeCreate = DateTime.Now;
                account.Active = true;
                account.UserRole = (byte) UserRole.EndUser;
                _repository.AddNewAccount(account);
            }
            return RedirectToLogin();
        }

        public ActionResult Login()
        {
            var model = new LoginModel()
                            {
                                ReturnUrl = Request.Path
                            };
            return View(model);
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            if (!ModelState.IsValid)
                return View(model);
            Account account = _repository.Login(model.UserName,model.Password);
            if (account == null)
            {
                ViewData[ViewDataName.ErrorMessage] = "Tài khoản không tồn tại";
                return View(model);
            }
            FormsAuthentication.SetAuthCookie(account.Id.ToString(),true);
            if (string.IsNullOrEmpty(model.ReturnUrl))
                return RedirectToHomePage();
            return Redirect(model.ReturnUrl.UrlDecode());
        }

        [HttpGet]
        public ActionResult LogOff(string returnUrl)
        {
            FormsAuthentication.SignOut();
            returnUrl = string.IsNullOrEmpty(returnUrl) ? "/" : returnUrl;
            return Redirect(returnUrl.UrlDecode());
        }
    }
}
